<template>
	<ComPop
		v-model="visible"
		width="50%"
		:title="dialogTitle"
		@saveSubmit="saveSubmit"
	>
		<el-form :model="form" :rules="rules" ref="formRef" label-width="110px">
			<!-- 运单基础信息 -->
			<el-card class="mb-4" shadow="never">
				<template #header>
					<span>运单基础信息</span>
				</template>
				<el-row :gutter="20">
					<el-col :span="24">
						<el-form-item label="运单号">
							<el-link type="primary" :underline="false">{{
								form.waybillNo
							}}</el-link>
							<el-button type="primary" size="small" class="ml-4">{{
								form.status
							}}</el-button>
						</el-form-item>
					</el-col>
					<el-col :span="10">
						<el-form-item label="始发地">
							<el-link type="info" :underline="false">{{
								form.origin
							}}</el-link>
						</el-form-item>
					</el-col>
					<el-col :span="10">
						<el-form-item label="目的地">
							<el-link type="info" :underline="false">{{
								form.destination
							}}</el-link>
						</el-form-item>
					</el-col>
				</el-row>
			</el-card>

			<!-- 收发货地址信息 - 仅在异常状态显示 -->
			<el-card v-if="canEditAddress" class="mb-4" shadow="never">
				<template #header>
					<div class="card-header">
						<span>收发货地址信息</span>
						<!-- <el-tag size="small" type="warning">可修改收发货地址</el-tag> -->
					</div>
				</template>

				<!-- 发货地址 -->
				<div class="address-section">
					<div class="address-header">
						<el-tag type="warning">发</el-tag>
					</div>
					<el-row :gutter="20">
						<el-col :span="8">
							<el-form-item label="联系人" prop="senderName">
								<el-input
									v-model="form.senderName"
									placeholder="请输入联系人"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="联系电话" prop="senderPhone">
								<el-input
									v-model="form.senderPhone"
									placeholder="请输入联系电话"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item>
								<el-button type="primary" @click="chooseAddressBook('sender')"
									>地址薄</el-button
								>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="8">
							<el-form-item label="地址简称" prop="senderShort">
								<el-input
									v-model="form.senderShort"
									placeholder="请输入地址简称"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="16">
							<el-form-item label="详细地址" prop="senderAddress">
								<el-input
									v-model="form.senderAddress"
									placeholder="请输入详细地址"
								/>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 收货地址 -->
				<div class="address-section">
					<div class="address-header">
						<el-tag type="success">收</el-tag>
					</div>
					<el-row :gutter="20">
						<el-col :span="8">
							<el-form-item label="联系人" prop="receiverName">
								<el-input
									v-model="form.receiverName"
									placeholder="请输入联系人"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="联系电话" prop="receiverPhone">
								<el-input
									v-model="form.receiverPhone"
									placeholder="请输入联系电话"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item>
								<el-button type="primary" @click="chooseAddressBook('receiver')"
									>地址薄</el-button
								>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="8">
							<el-form-item label="地址简称" prop="receiverShort">
								<el-input
									v-model="form.receiverShort"
									placeholder="请输入地址简称"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="16">
							<el-form-item label="详细地址" prop="receiverAddress">
								<el-input
									v-model="form.receiverAddress"
									placeholder="请输入详细地址"
								/>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-card>

			<!-- 车辆信息 -->
			<el-card class="mb-4" shadow="never">
				<template #header>
					<div class="card-header">
						<span>车辆信息</span>
						<!-- <el-tag v-if="!canEditVehicle" size="small" type="info">只读</el-tag>
              <el-tag v-else size="small" type="primary">可编辑</el-tag> -->
					</div>
				</template>
				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="运企名称" prop="companyId" required>
							<el-select
								v-model="form.companyId"
								placeholder="请选择运企"
								:disabled="!canEditVehicle"
							>
								<el-option
									v-for="item in companyList"
									:key="item.id"
									:label="item.name"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="司机姓名" prop="driverId" required>
							<el-select
								v-model="form.driverId"
								placeholder="请选择司机"
								@change="onDriverChange"
								:disabled="!canEditVehicle"
							>
								<el-option
									v-for="item in driverList"
									:key="item.id"
									:label="item.name"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="联系电话" prop="driverPhone" required>
							<el-input v-model="form.driverPhone" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="车牌号" prop="plateNo" required>
							<el-select v-model="form.plateNo" placeholder="请选择车牌号">
								<el-option
									v-for="item in carList"
									:key="item.no"
									:label="item.no"
									:value="item.no"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="计划发车时间" prop="planDepartTime" required>
							<el-date-picker
								v-model="form.planDepartTime"
								type="datetime"
								placeholder="选择日期时间"
								style="width: 100%"
								:disabled="!canEditVehicle"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="计划到达时间" prop="planArriveTime" required>
							<el-date-picker
								v-model="form.planArriveTime"
								type="datetime"
								placeholder="选择日期时间"
								style="width: 100%"
								:disabled="!canEditVehicle"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-card>
		</el-form>
		<!-- 地址簿选择弹窗 -->
		<AddressSelect ref="addressSelectRef" @select="handleAddressSelect" />
	</ComPop>
</template>

<script setup lang="ts">
import { ref, computed, reactive, nextTick, h, watch } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import AddressSelect from '/@/views/tscompany/CustomerMgmt/components/AddressSelect.vue';
const addressSelectRef = ref();
const currentAddressType = ref('');
const visible = ref(false);
const formRef = ref();
const form = reactive<any>({});

// Watch for company changes to reset driver and vehicle
watch(
	() => form.companyId,
	(newVal, oldVal) => {
		if (newVal !== oldVal && oldVal !== undefined) {
			form.driverId = undefined;
			form.driverPhone = '';
			form.plateNo = undefined;
		}
	},
);

// 下拉数据
const companyList = ref<any[]>([]);
const allDriverList = ref<any[]>([]);
const allCarList = ref<any[]>([]);
const driverList = computed(() => {
	if (!form.companyId) return [];
	return allDriverList.value.filter(
		(driver) => driver.companyId === form.companyId,
	);
});
const carList = computed(() => {
	if (!form.companyId) return [];
	return allCarList.value.filter((car) => car.companyId === form.companyId);
});
const callback = ref<((data: any) => void) | null>(null);

// 状态判断
const canEditAddress = computed(() => form.status === '异常');
const canEditVehicle = computed(
	() => form.status === '待接单' || form.status === '异常',
);
const dialogTitle = computed(() => {
	if (form.status === '异常') return '异常修改';
	if (form.status === '待接单') return '运单编辑';
	return '运单详情';
});

// 校验规则 - 动态规则
const rules = computed(() => {
	// 基础车辆信息验证（当可编辑时）
	const vehicleRules = canEditVehicle.value
		? {
				// 联系电话必填，且格式正确
				driverPhone: [
					{ required: true, message: '请输入联系电话', trigger: 'blur' },
					{
						pattern: /^1[3-9]\d{9}$/,
						message: '请输入正确的手机号',
						trigger: 'blur',
					},
				],
				companyId: [
					{ required: true, message: '请选择运企', trigger: 'change' },
				],
				driverId: [
					{ required: true, message: '请选择司机', trigger: 'change' },
				],
				plateNo: [
					{ required: true, message: '请选择车牌号', trigger: 'change' },
				],
				planDepartTime: [
					{ required: true, message: '请选择计划发车时间', trigger: 'change' },
				],
				planArriveTime: [
					{ required: true, message: '请选择计划到达时间', trigger: 'change' },
				],
			}
		: {};

	// 如果是异常状态，需要校验收货地址
	if (canEditAddress.value) {
		return {
			...vehicleRules,
			// 发货地址验证
			senderName: [
				{ required: true, message: '请输入发货联系人', trigger: 'blur' },
			],
			senderPhone: [
				{ required: true, message: '请输入发货电话', trigger: 'blur' },
				{
					pattern: /^1[3-9]\d{9}$/,
					message: '请输入正确的手机号',
					trigger: 'blur',
				},
			],
			senderShort: [
				{ required: true, message: '请输入地址简称', trigger: 'blur' },
			],
			senderAddress: [
				{ required: true, message: '请输入详细地址', trigger: 'blur' },
			],
			// 收货地址验证
			receiverName: [
				{ required: true, message: '请输入收货联系人', trigger: 'blur' },
			],
			receiverPhone: [
				{ required: true, message: '请输入收货电话', trigger: 'blur' },
				{
					pattern: /^1[3-9]\d{9}$/,
					message: '请输入正确的手机号',
					trigger: 'blur',
				},
			],
			receiverShort: [
				{ required: true, message: '请输入地址简称', trigger: 'blur' },
			],
			receiverAddress: [
				{ required: true, message: '请输入详细地址', trigger: 'blur' },
			],
		};
	}

	return vehicleRules;
});

/**
 * 打开弹窗
 */
function open(options: {
	waybill: any;
	companyList: any[];
	driverList: any[];
	carList: any[];
	onSubmit: (data: any) => void;
}) {
	// 重置表单
	Object.keys(form).forEach((key) => {
		delete form[key];
	});

	// 填充数据
	Object.assign(form, options.waybill);
	companyList.value = options.companyList;
	allDriverList.value = options.driverList;
	allCarList.value = options.carList;
	callback.value = options.onSubmit;

	// 显示弹窗
	visible.value = true;

	// 重置验证
	nextTick(() => {
		formRef.value?.clearValidate();
	});
}

/**
 * 司机变更时自动带出电话和默认车辆
 */
function onDriverChange(driverId: string) {
	const driver = driverList.value.find((d) => d.id === driverId);
	if (driver) {
		form.driverPhone = driver.phone;
		form.plateNo = driver.defaultCarNo;
	}
}

/**
 * 选择地址薄
 */
function chooseAddressBook(type: 'sender' | 'receiver') {
	currentAddressType.value = type;
	addressSelectRef.value?.open();
}
// 选择地址回调
const handleAddressSelect = (address: any) => {
	if (currentAddressType.value === 'sender') {
		form.senderName = address.contact;
		form.senderPhone = address.phone;
		form.senderShort = address.title;
		form.senderAddress = address.detail;
	} else {
		form.receiverName = address.contact;
		form.receiverPhone = address.phone;
		form.receiverShort = address.title;
		form.receiverAddress = address.detail;
	}
};

/**
 * 提交表单
 */
function saveSubmit() {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			callback.value && callback.value({ ...form });
			visible.value = false;
		}
	});
}

// 为了兼容默认导出，定义组件
defineOptions({
	name: 'WaybillEditDialog',
});

defineExpose({ open });
</script>

<style scoped>
.card-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.address-section {
	position: relative;
	margin-bottom: 20px;
	padding: 25px 15px 15px;
	border-radius: 4px;
	border: 1px solid #ebeef5;
}

.address-section:first-child {
	background-color: #fffbf0;
}

.address-section:last-child {
	background-color: #f0f9f0;
	margin-bottom: 0;
}

.address-header {
	position: absolute;
	top: -12px;
	left: 15px;
	background-color: #fff;
	padding: 0 8px;
}
</style>
